package makabakaquestionnaire.zutsoftware.framework.security.Service;

import cn.hutool.core.util.StrUtil;
import makabakaquestionnaire.zutsoftware.constant.Constants;
import makabakaquestionnaire.zutsoftware.entity.Users;
import makabakaquestionnaire.zutsoftware.exception.CustomException;
import makabakaquestionnaire.zutsoftware.framework.security.model.LoginUser;
import makabakaquestionnaire.zutsoftware.mapper.UsersMapper;
import makabakaquestionnaire.zutsoftware.utils.DateUtils;
import makabakaquestionnaire.zutsoftware.utils.redis.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * @author ：wjf
 * @date ：Created in 2022/2/20 14:05
 * @description：登陆认证方法
 * @modified By：
 */
@Service
public class AuthLoginService implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(AuthLoginService.class);
    @Autowired
    private RedisUtils redisUtils;
    @Resource
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UsersMapper usersMapper;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        //1.判断验证码是否正确
        if (StrUtil.isNotEmpty(code)) {   //开发测试，验证码为null，不进行验证了
            String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
            String captcha = redisUtils.get(verifyKey);
            redisUtils.remove(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {  //忽略验证大小写
                String msg = "验证码错误";
                return msg;
            }
        }
        // 2.进行用户验证
        return login0(username, password);
    }

    /**
     * 扫码登录验证，不需要验证码和uuid
     *
     * @param username
     * @param password
     * @return
     */
    public String login0(String username, String password) {
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 根据loginUser生成token,同时将loginUser存入到redis中
        return tokenService.createToken(loginUser);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = usersMapper.queryByName(username);
        if (users == null) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (users.getStatus() == "0") {
            log.info("登录用户：{} 已被停用.", username);
            throw new CustomException("对不起，您的账号：" + username + " 已停用");
        }
        users.setLastLoginTime(DateUtils.getNowDate());
        usersMapper.updateUsers(users);
        return buildLoginUser(users);
    }

    private LoginUser buildLoginUser(Users users) {
        //密码加密，明文密码被security抛异常
        users.setPassword(new BCryptPasswordEncoder().encode(users.getPassword()));
        return new LoginUser(users);//还未加入权限
    }
}
